package rs.arm.letthemusicplay;

import java.util.ArrayList;
import java.util.Iterator;

import rs.arm.letthemusicplay.filechooser.FileChooser;
import rs.arm.letthemusicplay.utilities.Constants;
import rs.arm.letthemusicplay.utilities.FileUtilities;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends Activity {
	private BroadcastReceiver receiver = null;

	private ArrayList<String> playlist = new ArrayList<String>();

	private TextView songTitle;
	private TextView durationOne;
	private TextView durationTwo;
	private SeekBar songSeekBar;
	private ImageButton btnPlay;
	private ImageButton btnNext;
	private ImageButton btnPrev;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private Menu menu;

	private boolean isPaused = false;
	private boolean isRepeat = false;
	private boolean isShuffle = false;

	private static int REQUEST_CODE_PLAYLIST = 1337; // leet
	private static int REQUEST_CODE_ADD_NEW_SONG = 1338;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		initViews();
		Intent intent = getIntent();
		String startFrom = intent.getStringExtra(Constants.INTENT_START_FROM);
		if (startFrom.equals(Constants.DIALOG_NAME_PLAYLIST_PICKER)) {
			makePlaylistFromDialog();
		} else if (startFrom.equals(Constants.ACTIVITY_NAME_FILE_CHOOSER)) {
			Intent i = getIntent();
			String path = i.getStringExtra(Constants.INTENT_GET_PATH);
			String name = i.getStringExtra(Constants.INTENT_GET_FILE_NAME);
			playlist.add(path + "/" + name);
		}

		Intent serviceIntent = new Intent(this, MediaPlayerService.class);
		serviceIntent.putStringArrayListExtra(Constants.EXTRA_PLAY_LIST, playlist);
		startService(serviceIntent);

		receiver = new MainActivityBroadcastReceiver();
		LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
				new IntentFilter(Constants.PLAYER_SERVICE_RESULT));
		// registerReceiver();
	}

	@Override
	protected void onDestroy() {
		LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_activity_menu, menu);
		this.menu = menu;

		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		i.putExtra(Constants.CODE_ACTION, Constants.ACTION_DRAW_STAR);
		sendBroadcast(i);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// Respond to the action bar's Up/Home button
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_star:
			starClicked();
			break;
		case R.id.action_change_playlist:
			Dialog d = new PlaylistPicker(this);
			d.show();
			break;
		case R.id.action_add_new_song:
			Intent fileChooserIntent = new Intent(this, FileChooser.class);
			startActivityForResult(fileChooserIntent, REQUEST_CODE_ADD_NEW_SONG);
			break;
		case R.id.action_play_favourites:
			playFavorites();
			break;
		case R.id.action_remove_from_playlist:
			removeFromPlaylist();
			break;
		case R.id.action_show_current_playlist:
			Intent playlistIntent = new Intent(this, PlayListActivity.class);
			playlistIntent.putStringArrayListExtra(Constants.EXTRA_PLAY_LIST, playlist);
			startActivityForResult(playlistIntent, REQUEST_CODE_PLAYLIST);
			break;
		case R.id.action_quit:
			Intent serviceIntent = new Intent(this, MediaPlayerService.class);
			stopService(serviceIntent);
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_CODE_PLAYLIST) {
				int songNumber = data
						.getIntExtra(Constants.EXTRA_SONG_NUMBER, Constants.ERROR_CODE);
				Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
				i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_PLAY);
				i.putExtra(Constants.EXTRA_SONG_NUMBER, songNumber);
				sendBroadcast(i);
			}
			if (requestCode == REQUEST_CODE_ADD_NEW_SONG) {
				String songName = data.getStringExtra(Constants.EXTRA_SONG_NAME);
				Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
				i.putExtra(Constants.CODE_ACTION, Constants.ACTION_ADD_NEW_SONG);
				i.putExtra(Constants.EXTRA_SONG_NAME, songName);
				sendBroadcast(i);
			}
		}
	}

	private void initViews() {
		songTitle = (TextView) findViewById(R.id.song_title);
		durationOne = (TextView) findViewById(R.id.dur_1);
		durationTwo = (TextView) findViewById(R.id.dur_2);
		btnPlay = (ImageButton) findViewById(R.id.btn_play_pause);
		btnPrev = (ImageButton) findViewById(R.id.btn_previous);
		btnNext = (ImageButton) findViewById(R.id.btn_next);
		btnRepeat = (ImageButton) findViewById(R.id.btn_repeat);
		btnShuffle = (ImageButton) findViewById(R.id.btn_suffle);
		songSeekBar = (SeekBar) findViewById(R.id.seek_bar);
	}

	public void btnPlayPauseClick(View v) {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		if (isPaused) {
			isPaused = false;
			i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_PLAY);
			// TODO adding song number or title
			Drawable replacer = getResources().getDrawable(R.drawable.button_grey_play);
			btnPlay.setImageDrawable(replacer);
			btnPlay.invalidate();
		} else {
			isPaused = true;
			i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_PAUSE);
			Drawable replacer = getResources().getDrawable(R.drawable.button_grey_pause);
			btnPlay.setImageDrawable(replacer);
			btnPlay.invalidate();
		}
		sendBroadcast(i);
	}

	public void btnPrevClick(View v) {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_PREVIOUS);
		sendBroadcast(i);
	}

	public void btnNextClick(View v) {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_NEXT);
		sendBroadcast(i);
	}

	public void btnRepeatClick(View v) {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		if (isRepeat) {
			isRepeat = false;
			i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_REPEAT);
			Drawable replacer = getResources().getDrawable(R.drawable.gnome_media_playlist_repeat);
			btnRepeat.setImageDrawable(replacer);
			btnRepeat.invalidate();
		} else {
			isRepeat = true;
			i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_REPEAT);
			Drawable replacer = getResources().getDrawable(
					R.drawable.gnome_media_playlist_repeat_pressed);
			btnRepeat.setImageDrawable(replacer);
			btnRepeat.invalidate();
		}
		sendBroadcast(i);
	}

	public void btnShuffleClick(View v) {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		if (isShuffle) {
			isShuffle = false;
			i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_SHUFFLE);
			Drawable replacer = getResources().getDrawable(R.drawable.gnome_media_playlist_shuffle);
			btnShuffle.setImageDrawable(replacer);
			btnShuffle.invalidate();
		} else {
			isShuffle = true;
			i.putExtra(Constants.CODE_ACTION, Constants.ACTION_BTN_SHUFFLE);
			Drawable replacer = getResources().getDrawable(
					R.drawable.gnome_media_playlist_shuffle_pressed);
			btnShuffle.setImageDrawable(replacer);
			btnShuffle.invalidate();
		}
		sendBroadcast(i);
	}

	private void starClicked() {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		i.putExtra(Constants.CODE_ACTION, Constants.ACTION_STAR_CLICKED);
		sendBroadcast(i);
	}

	private void playFavorites() {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		i.putExtra(Constants.CODE_ACTION, Constants.ACTION_PLAY_FAVORITES);
		sendBroadcast(i);
	}

	private void removeFromPlaylist() {
		Intent i = new Intent(Constants.ACTION_ACTIVITY_TO_PLAYER_SERVICE);
		i.putExtra(Constants.CODE_ACTION, Constants.ACTION_REMOVE_FROM_PLAYLIST);
		sendBroadcast(i);
	}

	private void updateStarIcon(String star) {
		MenuItem starItem = menu.findItem(R.id.action_star);
		if (star.equals(Constants.MSG_UPDATE_FALSE)) {
			starItem.setIcon(android.R.drawable.star_off);
		} else {
			starItem.setIcon(android.R.drawable.star_on);
		}
		invalidateOptionsMenu();
	}

	private void makePlaylistFromDialog() {
		if (playlist != null) {
			playlist = new ArrayList<String>();
		} else {
			playlist.clear();
		}
		Iterator<String> iter = PlaylistPicker.pickedLists.iterator();
		while (iter.hasNext()) {
			playlist.addAll(FileUtilities.getSongsFromPlaylist(iter.next()));
		}
	}

	public class MainActivityBroadcastReceiver extends BroadcastReceiver {

		public MainActivityBroadcastReceiver() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			int code = intent.getIntExtra(Constants.CODE_UPDATE, -1);
			if (code != -1) {
				switch (code) {
				case Constants.SEND_UPDATE_SEEKBAR:
					String seekBarUpdate = intent.getStringExtra(Constants.MSG_UPDATE_SEEKBAR);
					int update = Integer.parseInt(seekBarUpdate);
					songSeekBar.setProgress(update);
					songSeekBar.invalidate();
					break;
				case Constants.SEND_UPDATE_DURATION_1:
					String dur1 = intent.getStringExtra(Constants.MSG_UPDATE_DURATION_1);
					durationOne.setText(dur1);
					durationOne.invalidate();
					break;
				case Constants.SEND_UPDATE_DURATION_2:
					String dur2 = intent.getStringExtra(Constants.MSG_UPDATE_DURATION_2);
					durationTwo.setText(dur2);
					durationTwo.invalidate();
					break;
				case Constants.SEND_UPDATE_SONG_TITLE:
					String name = intent.getStringExtra(Constants.MSG_UPDATE_SONG_TITLE);
					songTitle.setText(name);
					songTitle.invalidate();
					break;
				case Constants.SEND_UPDATE_SONG_STAR:
				case Constants.SEND_UPDATE_STAR:
					String star = intent.getStringExtra(Constants.MSG_UPDATE_STAR);
					updateStarIcon(star);
				}
			}
		}

	}

}
